<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class CustomerController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:customer');
    }

    //TODO: 这个函数很可能没用
    public function index(){
        return view('home');
    }

    public function displayProfile(){
        $customer = Auth::user();
        return view('profile', ['customer' => $customer]);
    }

    public function profile(Request $request){
        $customer = Auth::user();
        $this->validate($request, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:customers,email,' . $customer->id],
            'gender' => ['required', 'numeric'],
            'phone' => ['required', 'string', 'regex:/(1)[0-9]{10}/', 'unique:customers,phone,' . $customer->id],
        ],[
            'name.required' => '姓名必填',
            'name.max' => '请注意姓名长度',
            'email.required' => '邮箱地址必填',
            'email.email' => '请填写正确的邮箱格式',
            'email.max' => '请注意邮箱长度',
            'email.unique' => '邮箱已被注册',
            'gender.required' => '请填写性别',
            'gender.between' => '请填写正确的性别',
            'phone.required' => '手机号码必填',
            'phone.regex' => '请填写正确的手机号码',
            'phone.unique' => '手机号码已被注册',
        ]);
        $customer->fill($request->all());
        $customer->update();
        return back()->with('success', '修改资料成功');
    }

    public function showChangePasswordForm(){
        return view('changePassword');
    }

    public function changePassword(Request $request){
        $user = Auth::user();
        if (!Hash::check($request->get('old-password'), $user->password)){
            return back()->with('error', '验证密码失败');
        }

        if (Hash::check($request->get('password'), $user->password)){
            return back()->with('error', '新密码不能与当前密码相同');
        }

        $this->validate($request, [
            'old-password' => ['required'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ], [
            'old-password.required' => '请填写当前密码',
            'password.required' => '请填写密码',
            'password.min' => '密码太短',
            'password.confirmed' => '两次密码不一致',
        ]);

        $user->password = bcrypt($request->get('password'));
        $user->update();
        return back()->with('success', '密码修改成功');
    }
}
